<!-- 结算管理 -->
<template>
    <div >
        <div class='table-page-search-wrapper'>
            <a-form layout='inline'>
               <a-row :gutter='48'>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="项目名称">
                            <a-input v-model="projectName" placeholder="请输入项目名称" allow-clear></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="所属客户">
                            <a-input v-model="customerName" placeholder="请输入所属客户" allow-clear></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="所属公司">
                            <a-input v-model="companyName" placeholder="请输入所属公司" allow-clear></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="结算单名称">
                            <a-input v-model="settlementName" placeholder="请输入结算单名称" allow-clear></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="状态">
                            <a-select v-model="state" placeholder="请选择" allow-clear @change="getData">
                                <a-select-option v-for="item in stateList" :key="item.id" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md='16' :sm='24'>
                        <a-form-item label="上传时间">
                            <a-range-picker @change="onDateChange" />
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item >
                            <a-button type='primary' style="margin-right: 20px;" @click="getData">查询</a-button>
                            <!-- <a-button type='primary' style="margin-left: 20px;" @click="getData">申请验收结算</a-button> -->
                            <a-upload
                                style="display: inline-block"
                                :before-upload="beforeUpload"
                                @change="handleChange"
                                :fileList="[]"
                                v-if="hasPower('uploadSettlementExcel')"
                            >
                                <a-button> <a-icon type="upload" />申请验收结算</a-button>
                            </a-upload>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>  

        <a-table rowKey="id" :loading="isload" :columns="columns" :data-source="dataList" @change="handleTableChange" :pagination="{ total: total ,showSizeChanger: true,pageSize: size,}" size="small" :scroll="{ x: 1800, }">
            <div slot="state" slot-scope="state">
                <div v-for="(item,i) in stateList" :key="item.id">
                    <a-tag v-if="item.id == state" :color="colors[i%13]">{{item.name}}</a-tag>
                </div>
            </div>
            <div slot="remark" slot-scope="remark">
                <ellipsis :length="26" tooltip>{{ remark == '' || !remark ? '-' : remark }}</ellipsis>
            </div>
            <div slot="operation" slot-scope="text,record">
                <div class="editable-row-operations">
                    <a-button type="link" @click="detail(record)">详情</a-button>
                    <a-popconfirm
                        title="是否支付当前结算单?"
                        ok-text="确定"
                        cancel-text="取消"
                        @confirm="pay(record)"
                        v-if="record.state == 1 && hasPower('settlementPay')"
                    >
                        <a-button type="link">支付</a-button>
                    </a-popconfirm>
                    <a-popconfirm
                        title="是否删除当前结算单?"
                        ok-text="确定"
                        cancel-text="取消"
                        @confirm="del(record)"
                        v-if="record.state == 6 || record.state == 9"
                    >
                        <a-button type="link" class="danger">删除</a-button>
                    </a-popconfirm>
                </div>
            </div>
        </a-table>

        <!-- 去支付 -->
        <a-modal 
            v-model="payVisible" 
            title="确认支付"
            @ok="payHandleOk" 
            width="75%"
            @cancel="payVisible = false">
            <div>
                <a-descriptions :title="`结算金额${paySettlement.amount}`">
                    <a-descriptions-item label="订单总金额">{{paySettlement.totalAmount}}</a-descriptions-item>
                    <a-descriptions-item label="服务费">{{paySettlement.serviceAmount}}</a-descriptions-item>
                    <a-descriptions-item label="服务费率">{{paySettlement.serviceRate}}%</a-descriptions-item>
                    <a-descriptions-item label="结算单名称">{{paySettlement.settlementName}}</a-descriptions-item>
                    <a-descriptions-item label="所属公司">{{paySettlement.companyName}}</a-descriptions-item>
                    <a-descriptions-item label="所属客户">{{paySettlement.customerName}}</a-descriptions-item>
                    <a-descriptions-item label="明细笔数">{{paySettlement.detailedCount}}</a-descriptions-item>
                    <a-descriptions-item label="项目名称">{{paySettlement.projectName}}</a-descriptions-item>
                </a-descriptions>
                <a-form-model :label-col="{ span:3 }" :wrapper-col="{ span: 15 }" v-if="hasPayPassword && needPayPassword">
                    <a-form-model-item label="支付密码" labelAlign="left">
                        <a-input v-model="payPassword" placeholder="请输入支付密码" allow-clear/>
                    </a-form-model-item>
                </a-form-model>
                <a-divider/>
                <div>可用支付账户</div>
                <a-radio-group v-model="accountId" @change="selAccount">
                    <a-radio :style="radioStyle" v-for="account in accountList" :key="account.id" :value="account.id">账户名称：{{account.accountName}}({{account.bankAccount}})，账户余额：{{account.amount}}，联动设置：{{account.linkageType |linkageTypeFilter}}</a-radio>
                </a-radio-group>
            </div>
        </a-modal>
    </div>
</template>

<script>
import { columns } from './table';
import { getSettlementList , uploadSettlementExcel , passSettlementOrder , refuseSettlementOrder , authSettlementOrder , deleteSettlementOrder , settlementPay } from '@/api/services/settlement';
import { getAccountBySettlement , getHasPayPassword } from '@/api/services/account';
import { Ellipsis } from '@/components';
export default {
    components: {
        Ellipsis,
    },
    data () {
        return {
            projectName: '', // 项目名称
            customerName: '', // 客户名称
            companyName: '', // 公司名称
            settlementName: '', // 结算单名称
            startTime: '',
            endTime: '',
            state: undefined,
            stateList: [
                { id: 0, name: '待审核'},
                { id: 1, name: '待支付'},
                { id: 2, name: '待授权'},
                { id: 3, name: '已支付'},
                { id: 4, name: '部分支付失败'},
                { id: 5, name: '已驳回'},
                { id: 6, name: '已取消'},
                { id: 7, name: '支付失败'},
                { id: 8, name: '支付中'},
                { id: 9, name: '已结束'},
            ],
            dataList: [],
            page: 1,
            size: 10,
            total: 0,
            isload: false,
            columns,
            colors: ['blue','purple','cyan','green','orange','red','pink','brown','indigo','lime','purple','teal','yellow','amber'],
            rules: {
                refuseReason: [{ required: true, message: '请输入拒绝原因', trigger: 'blur' }]
            },
            refuse: {
                refuseReason: '',
            },
            visible: false,
            settlementId: '',
            payVisible: false,
            paySettlement: {
                id: '',
                amount: '',
                totalAmount: '',
                serviceAmount: '',
                serviceRate: '', 
                settlementName: '',
                companyName: '',
                customerName: '',
                detailedCount: '',
                projectName: '',
            },
            accountList: [], // 已关联账户列表
            accountId: undefined,
            radioStyle: {
                display: 'block',
                height: '30px',
                lineHeight: '30px',
            },
            payPassword: '',
            hasPayPassword: false,
            needPayPassword: false,
        };
    },
    created(){
        this.getData();
    },
    methods: {
        // 日期筛选
        onDateChange(date,dateStr){
            console.log(date,dateStr)
            if(date.length > 0){
                this.startTime = `${dateStr[0]}`
                this.endTime = `${dateStr[1]}`
            }else{
                this.startTime = ''
                this.endTime = ''
            }
            this.getData()
        },
        // 获取结算列表数据
        getData(){
            let _this = this;
            _this.isload = true;
            const params = {
                'startTime': _this.startTime,
                'endTime': _this.endTime,
                'projectName': _this.projectName,
                'customerName': _this.customerName,
                'companyName': _this.companyName,
                'settlementName': _this.settlementName,
                'state': _this.state,
                'pageSize': _this.size,
                'pageIndex': _this.page,
            }
            getSettlementList(params)
            .then(res=> {
                _this.isload = false;
                if(res.success){
                    _this.dataList = res.data;
                    _this.total = res.totalCount;
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData()
        },
        // 上传结算单
        beforeUpload(file) {
            return false;
        },
        handleChange({file,fileList}){
            let _this = this
            const formData = new FormData();
            formData.append('file',file)
            uploadSettlementExcel(formData)
            .then(res=>{
                if(res.success){
                    _this.$router.push({path: '/companysSettlement/excelUpload', query: { 'fileData': JSON.stringify(res.data),}})
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 通过结算审核
        pass(item){
            let _this = this;
            passSettlementOrder(item.id)
            .then(res => {
                if(res.success){
                    _this.$notification['success']({
                        message: '温馨提示',
                        description: '操作成功',
                        duration: 8
                    });
                    _this.getData();
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 拒绝结算单
        refuseOrder(item){
            this.settlementId = item.id;
            this.visible = true;
        },
        handleOk(){
            let _this = this
            _this.$refs.ruleForm.validate(valid => {
                if(valid){
                    const params = {
                        'settlementId': _this.settlementId,
                        'refuseReason': _this.refuse.refuseReason
                    }
                    refuseSettlementOrder(params)
                    .then(res=>{
                        if(res.success){
                            _this.visible = false;
                            _this.getData();
                            _this.$notification['success']({
                                message: '温馨提示',
                                description: '操作成功',
                                duration: 8
                            })
                        }else{
                            _this.$notification['error']({
                                message: '温馨提示',
                                description: res.errMessage,
                                duration: 8
                            })
                        }
                    })
                }
            })
        },
        // 结算单授权
        auth(item){
            let _this = this;
            authSettlementOrder(item.id)
            .then(res => {
                if(res.success){
                    _this.$notification['success']({
                        message: '温馨提示',
                        description: '操作成功',
                        duration: 8
                    });
                    _this.getData();
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 删除结算单
        del(item){
            let _this = this;
            deleteSettlementOrder(item.id)
            .then(res => {
                if(res.success){
                    _this.$notification['success']({
                        message: '温馨提示',
                        description: '操作成功',
                        duration: 8
                    });
                    _this.getData();
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 详情
        detail(item){
            this.$router.push({ path: '/companysSettlement/detail', query: { 'settlementId': item.id }})
        },
        // 去支付
        pay(item){
            let _this = this;
            _this.paySettlement = JSON.parse(JSON.stringify(item));
            _this.accountId = undefined;
            _this.accountList = [];
            getAccountBySettlement(item.id)
            .then(res => {
                if(res.success){
                    _this.accountList = res.data
                    _this.payVisible = true;
                    if(res.data.length > 0){
                        _this.accountId = res.data[0].id
                        _this.getHasPaypassword(_this.accountId)
                        if(res.data[0].needDealPassword == '1'){
                            _this.needPayPassword = true;
                        }else{
                            _this.needPayPassword = false;
                        }
                    }
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 确认支付
        payHandleOk(){
            let _this = this;
            if(_this.accountId == undefined){
                _this.$message.warning('请先与该结算单客户绑定业务账号，再进行支付操作！');
                return;
            }
            if(_this.hasPayPassword && _this.needPayPassword){
                if(_this.payPassword == ''){
                    _this.$message.warning('请输入交易密码！');
                    return;
                }
            }
            const params = {
                'settlementId': _this.paySettlement.id,
                'accountId': _this.accountId,
                'payPassword': _this.payPassword,
            }
            settlementPay(params)
            .then(res => {
                if(res.success){
                    _this.$notification['success']({
                        message: '温馨提示',
                        description: '已提交支付',
                        duration: 8
                    })
                    _this.payVisible = false
                    _this.getData();
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        // 获取是否设置过交易密码
        getHasPaypassword(accountId){
            let _this = this
            getHasPayPassword(accountId)
            .then(res=>{
                if(res.success){
                    _this.hasPayPassword = res.data;
                }else{
                    _this.$notification['error']({
                        message: '温馨提示',
                        description: res.errMessage,
                        duration: 8
                    })
                }
            })
        },
        selAccount(e){
            this.getHasPaypassword(e.target.value)
            var account = this.accountList.find(item => item.id == e.target.value);
            if(account.needDealPassword == '1'){
                this.needPayPassword = true;
            }else{
                this.needPayPassword = false;
            }
        }
    }
}

</script>
<style scoped>

</style>